package com.craftplay.service;

import com.alibaba.fastjson.JSONObject;
import com.craftplay.util.CraftPlayUtil;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by Pason on 2018/5/18.
 */
@Service
public class QiniuService {

    @Autowired
    private Environment env;

    private static final Logger logger = LoggerFactory.getLogger(QiniuService.class);

    //设置好账号的ACCESS_KEY和SECRET_KEY
    String ACCESS_KEY = "TKPTZgE5YdHyk8eJzz3CwYzuVUiJCQmCTgvwd4Wu";
    String SECRET_KEY = "HNEqRM3tIinFLLG-iezRLwftQu8j9MZ_iM7l8f5o";
    //要上传的空间
    String bucketname = "craft";

    Configuration cfg = new Configuration(Zone.zone0());

    //密钥配置
    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    //创建上传对象
    UploadManager uploadManager = new UploadManager(cfg);

    private static String QINIU_IMAGE_DOMAIN = "http://img.playpro.live/";

    //简单上传，使用默认策略，只需要设置上传的空间名就可以了
    public String getUpToken() {
        return auth.uploadToken(bucketname);
    }

    public String saveImage(MultipartFile file) throws IOException {
        try {
            int dotPos = file.getOriginalFilename().lastIndexOf(".");
            if (dotPos < 0) {
                return null;
            }
            String fileExt = file.getOriginalFilename().substring(dotPos + 1).toLowerCase();
            if (!CraftPlayUtil.isFileAllowed(fileExt)) {
                return null;
            }

            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;

            String storeLocation = "/data/tomcat-8.5.32/webapps/temp4/" + fileName;
            //压缩图片
            if (env.getProperty("isDebug").equals("true")) {
                storeLocation = "D:\\test\\" + fileName;
            }

            Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.4f).outputFormat("jpg").toFile(storeLocation);

            logger.info("上传图片：" + fileName);

            //调用put方法上传
            File upFile = new File(storeLocation);
            Response res = uploadManager.put(upFile, fileName, getUpToken());

            logger.info("七牛信息：" + res.bodyString());

            //打印返回的信息
            if (res.isOK() && res.isJson()) {
                return QINIU_IMAGE_DOMAIN + JSONObject.parseObject(res.bodyString()).get("key");
            } else {
                logger.error("七牛异常:" + res.bodyString());
                return null;
            }
        } catch (QiniuException e) {
            // 请求失败时打印的异常的信息
            logger.error("七牛异常:" + e.getMessage());
            return null;
        }
    }
}

